<template>
  <div class="page">
    
    <div id="login">
      <div class="logo">
        <img src="/static/logo.png">
        <p>{{$t('猴趣乐')}}</p>
        
      </div>
      <group label-align="justify" label-width="4.5em" label-margin-right="1em">
        <x-input type="tel" ref="phone" @on-change="change" :readonly="phoneReadonly" v-model="phone" :placeholder="$t('输入手机号')">
          <div slot="label" class="prefix">
            <select v-model="prefix">
              <option v-for="(item,index) in region" :value="item.val" :key="index">{{ item.val }}</option>
            </select>
          </div>
        </x-input>
        <x-input type="number" v-model="code" :placeholder="$t('输入验证码')" :min="6" :max="6" v-show="showCode" class="weui-vcode">
          <x-button id="sendCode" slot="right" :disabled="disabled" type="primary" mini>{{ $t(btnText) }}</x-button>
        </x-input>
        <x-input type="password" :is-type="isPassword" ref="phone" v-model="password" v-if="showPwd" :placeholder="$t(placeholder)"></x-input>
        <x-input :placeholder="$t('输入邀请码（选添）')" v-if="showinv" v-model="inv"></x-input>
      </group>
      <box gap="20px 0">
        <x-button id="next" v-show="showNext" :disabled="!isGtInit || !phoneValid">{{$t('下一步')}}</x-button>
        <p class="terms" v-show="showNext">{{$t('点击下一步即表示你已同意')}}
          <router-link to="/terms">《{{$t('用户协议')}}》</router-link>
        </p>
        <x-button @click.native="login" v-show="!showNext">{{$t('登录')}}</x-button>
      </box>
      <div class="more" v-if="!showNext">
        <div @click="forgetPwd" v-if="showForget">{{$t('忘记密码?')}}</div>
        <div @click="gobackLogin" v-else>{{$t('去登录')}}</div>
      </div>
    </div>
  </div>
</template>



<script>
  import {
    Group,
    XInput,
    XButton,
    Box
  } from 'vux'
  import '../plugins/geetest'
  export default {
    components: {
      Group,
      XInput,
      XButton,
      Box
    },
    data() {
      return {
        inv:'',
        phone: null,
        code: null,
        phoneValid: false,
        disabled: false,
        btnText: '发送验证码',
        countdown: 60,
        password: '',
        placeholder: "输入密码",
        showCode: false,
        showPwd: false,
        showinv: false,
        showNext: true,
        phoneReadonly: false,
        isPassword: function(str) {
          // (长度在6~18之间，只能包含字母、数字)
          var reg = /^[a-zA-Z0-9]{6,18}$/;
          var res = reg.test(str);
          return {
            valid: res,
            msg: res ? '' : '密码格式不符合要求'
          }
        },
        sendCodeType: 'login',
        showForget: false,
        isGtInit: false,
        prefix: '+86',
        region: [{
            val: '+86',
            len: 11
          },
          {
            val: '+852',
            len: 8
          },
          {
            val: '+853',
            len: 8
          },
          {
            val: '+886',
            len: 10
          }
        ],
        gtParams: {},
        lang: ''
      }
    },
    
    mounted() {
      this.$nextTick(function() {
        this.$vux.loading.hide()
        this.lang = localStorage["lang"] || 'zh-CN'
      })
    },
    watch: {
      phoneValid(newVal, oldVal) {
        if (newVal && !this.isGtInit) {
          this.initGeetest()
        }
      }
    },
    methods: {
      change(val) {
        if (val) {
          // 校验手机号
          // this.phoneValid = this.$refs.phone.valid
          // this.initGeetest()
          switch (this.prefix) {
            case this.region[0].val:
              if (val.length == this.region[0].len) {
                this.phoneValid = true
              } else {
                this.phoneValid = false
              }
              break;
            case this.region[1].val:
              if (val.length == this.region[1].len) {
                this.phoneValid = true
              } else {
                this.phoneValid = false
              }
              break;
            case this.region[2].val:
              if (val.length == this.region[2].len) {
                this.phoneValid = true
              } else {
                this.phoneValid = false
              }
              break;
            case this.region[3].val:
              if (val.length == this.region[3].len) {
                this.phoneValid = true
              } else {
                this.phoneValid = false
              }
              break;
          }
        } else {
          this.phoneValid = false
        }
      },
      // geetest
      initGeetest() {
        var that = this
        var timer = setTimeout(() => {
          this.$vux.loading.show({
            text: this.$t('加载中')
          })
        }, 300)
        this.$http.post(`/geeTest/startCaptcha`, {
          phone: this.phone
        }).then((res) => {
          if (res.code == 200) {
            var data = JSON.parse(res.result)
            window.initGeetest({
              gt: data.gt,
              challenge: data.challenge,
              offline: !data.success,
              new_captcha: data.new_captcha,
              product: 'bind'
            }, function(captchaObj) {
              document.getElementById('sendCode').addEventListener('click', function() {
                if (that.phoneValid) {
                  captchaObj.verify();
                }
              });
              document.getElementById('next').addEventListener('click', function() {
                if (that.phoneValid) {
                  captchaObj.verify();
                }
              });
              captchaObj.onReady(function() {
                that.isGtInit = true
                clearTimeout(timer);
                that.$vux.loading.hide()
              });
              captchaObj.onSuccess(function() {
                var result = captchaObj.getValidate();
                that.gtParams = result
                that.sendCode(result, captchaObj)
              });
              captchaObj.onError(function() {
                // 出错啦，可以提醒用户稍后进行重试
                that.$vux.toast.show({
                  text: that.$t('出错啦~请稍后再试')
                })
              });
            })
          } else if (res.code == 602) {
            // 无须验证码
            clearTimeout(timer);
            that.$vux.loading.hide()
            that.isGtInit = true
            document.getElementById('sendCode').addEventListener('click', function() {
              if (that.phoneValid) {
                that.sendCode()
              }
            });
            document.getElementById('next').addEventListener('click', function() {
              if (that.phoneValid) {
                that.sendCode()
              }
            })
          } else {
            that.$vux.toast.show({
              text: that.$t('出错啦~请稍后再试')
            })
          }
        }).catch(function(error) {});
      },
      // 发送验证码
      sendCode(gtParams, captchaObj) {
        if (this.phoneValid) {
          this.$http.post(`/users/code`, {
            phone: this.phone,
            areaCode: this.prefix,
            type: this.sendCodeType,
            challenge: gtParams ? gtParams.geetest_challenge : '',
            validate: gtParams ? gtParams.geetest_validate : '',
            seccode: gtParams ? gtParams.geetest_seccode : ''
          }).then((res) => {
            // 新用户
            if (res.code == 200) {
              // 如果是老用户 忘记密码开始倒计时
              // if (this.sendCodeType == 'find') {
              // }
              this.countDown60()
              this.$vux.toast.text(res.msg)
              this.showPwd = true
              this.showinv = true
              this.showCode = true
              this.showNext = false
              this.phoneReadonly = true
              this.placeholder = '请设置密码（长度6~18位）'
              // 老用户
            } else if (res.code == 606) {
              this.showPwd = true
              this.showinv = false;
              this.phoneReadonly = true
              this.showNext = false
              this.showForget = true
            } else {
              this.$vux.alert.show({
                title: '提示',
                content: res.msg
              })
              if (captchaObj) {
                captchaObj.reset(); // 调用该接口进行重置
              }
            }
          }).catch(function(error) {});
        } else {
          this.$vux.toast.text(this.$t('手机号码格式不正确'))
        }
      },
      // 忘记密码
      forgetPwd() {
        this.sendCodeType = 'find';
        this.showForget = false;

        this.showCode = true;
        this.placeholder = '请设置密码（长度6~18位）'
      },
      gobackLogin() {
        this.showForget = true;
        this.showCode = false;
        this.showinv = false;
        this.placeholder = '输入密码'
      },
      // 登录
      login() {
        if (!this.phoneValid) {
          this.$vux.toast.text(this.$t('手机号码格式不正确'))
          return
        }
        this.$vux.loading.show({
          text: this.$t('登录中')
        })

        var url = '/users/login';
        if(this.showCode){
        url = '/users/register';
        }
        if(this.sendCodeType == 'find'){
        url = '/users/changepwd';
        }
        this.$http.post(url, {
          phone: this.phone,
          code: this.code,
          // this.JsEncrypt(this.password)
          pwd: this.JsEncrypt(this.password),
          fromCode: this.inv
        }).then((res) => {
          this.$vux.loading.hide()
          
          if (res.code == 200) {
            localStorage.setItem("token_2", res.result.token)            
            var path=localStorage["loginpath"];
            if(path){
              localStorage.removeItem("loginpath");
              this.$router.replace( path );
            }else{
              this.$router.replace('/home');
            }
          } else {
            this.$vux.toast.text(res.msg)
          }
        }).catch(function(error) {});
      },
      countDown60() {
        var countdown = this.countdown
        if (countdown == 0) {
          this.disabled = false;
          this.btnText = '发送验证码'
          this.countdown = 60;
          return;
        } else {
          this.disabled = true;
          this.btnText = "重新发送(" + countdown + ")";
          this.btnText = this.$t('重新发送') + `(${countdown})`;
          this.countdown--;
        }
        var that = this;
        setTimeout(function() {
          that.countDown60()
        }, 1000)
      }
      
    }
  }
</script>

<style lang="scss" scoped>
  .page {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    padding-bottom: 0;
    background: #00182c url(/static/bg2.jpg) no-repeat;
    background-size: contain;
  }
  .header {
    position: absolute;
    right: 10px;
    top: 10px;
    .lang {
      width: 24px;
      height: 24px;
    }
    
  }
  .logo {
    text-align: center;
    color: #fff;
    font-size: 26px;
    line-height: 1;
    img {
      width: 84px;
      border-radius: 50%;
      margin-bottom: 10px;
    }
    span {
      font-size: 12px;
      display: inline-block;
      background: #4CAF50;
      color: #fff;
      padding: 2px 8px;
      border-radius: 10px;
    }
  }
  .terms {
    font-size: 10px;
    color: #908888;
    text-align: center;
    padding: 10px;
    a {
      color: $link;
    }
  }
  .more {
    text-align: center;
    font-size: 12px;
    color: #fff;
    div {
      padding: 5px;
    }
  }
  .prefix {
    // width: 60px;
    height: 44px;
    overflow: hidden;
    border-right: 1px solid #efefef;
    select {
      text-align: center;
      font-size: 14px;
      padding: 0 10px;
      height: 100%;
      border: none;
      outline: none;
      background: #fff;
      -webkit-appearance: none;
      -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    }
  }
</style>
<style lang="scss">
  #login {
    width: 80%;
    .weui-cell {
      padding: 0;
      margin-top: 10px;
      background-color: #fff;
      border-radius: 5px;
      overflow: hidden;
      &:before {
        display: none;
      }
      &:after {
        display: none;
      }
    }
    .weui-input {
      height: 44px;
      color: #000;
      padding: 0 12px;
      font-size: 14px;
    } // input::-webkit-input-placeholder {
    //   color: #fff;
    //   font-size: 14px;
    // }
    .weui-cells {
      background-color: transparent;
      &:before {
        display: none;
      }
      &:after {
        display: none;
      }
    }
    .weui-btn {
      color: #347df5;
      transition: .3s;
    }
    .weui-btn_mini {
      color: #fff;
      padding: 0 10px;
      margin-right: 5px;
    }
    .weui-icon-warn {
      color: #ff9800;
    }
    .weui-btn_disabled {
      color: rgba(0, 0, 0, 0.3);
      background-color: #e6e6e6;
    }
  }
</style>

